package com.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.helper.DBHelper;
import com.model.QuestionJudge;

public class QuestionJudgeDao {
	
	private QuestionJudge toQuestionJudge(Map<String, Object> data) 
	{
		QuestionJudge q = new QuestionJudge();
		q.setId((Integer)data.get("id"));
		q.setContent((String)data.get("content"));
		q.setAnswer(data.get("answer") + "");
		return q;
	}
	
	
	public List<QuestionJudge> getAll() 
	{
		List<QuestionJudge> result = new ArrayList<QuestionJudge>();
		String sql = "select * from que_judge";
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result.add(toQuestionJudge(ele));
		}
		return result;
	}



	public Boolean add(String cont, String ans) {
		int i = ans.equals("true")? 1 : 0;
		String sql = "INSERT INTO `que_judge` (`content`, `answer`) VALUES ('" + cont +"', '"+i+"')";
		DBHelper db = new DBHelper();
		return db.update(sql, null);
	}


	public QuestionJudge getById(Integer queId) {
		QuestionJudge result = new QuestionJudge();
		String sql = "select * from que_judge where id=" + queId;
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result = toQuestionJudge(ele);
		}
		return result;
	}

    public boolean edit(int qid, String cont, String ans) {
		String sql = "UPDATE `que_judge` SET `content` = ?, `answer` = ? WHERE `id` = ?;";
		List<Object> param = new ArrayList<>();
		param.add(cont);
		param.add(ans.toLowerCase().equals("true")? 1 : 0);
		param.add(qid);
		DBHelper db = new DBHelper();
		return db.update(sql, param);
    }

	public boolean updateAnswer(Integer qid, String ans) {
		String sql = "UPDATE `que_judge` SET `answer` = ? WHERE `id` = ?;";
		List<Object> param = new ArrayList<>();
		param.add(ans.toLowerCase().equals("true")? 1 : 0);
		param.add(qid);
		DBHelper db = new DBHelper();
		return db.update(sql, param);
	}
}
